#include <iostream>
#include <string>
#include <mysql/mysql.h>
#define HOST "127.0.0.1"
#define USER "xsc"
#define PASSWORD "Xsc.200411"
#define DB "study"
#define PORT 3306


int main()
{
    // 获取mysql客户端版本
    //std::cout << "mysql version->" << mysql_get_client_info() << std::endl;

    MYSQL* mysql = mysql_init(nullptr);
    if(mysql==nullptr) {
        std::cerr << "init mysql error" << std::endl;
        return 1;
    }
    if(!mysql_real_connect(mysql, HOST, USER, PASSWORD, DB, PORT, nullptr, 0)) {
        std::cerr << "mysql connect error" << std::endl;
        return 2;
    }

    std::cout << "mysql connect!" << std::endl;
    //std::string sql = "insert into user (name, age) values ('李四', 38);";
    //std::string sql = "update user set name='lisi' where name='李四';";
    //std::string sql = "delete from user where id=3;";
    std::string sql = "select * from user;";
    int n = mysql_query(mysql, sql.c_str());
    if(n != 0) {
        std::cerr << sql << "fail-> " << n << std::endl;
        return 3;
    }else {
        std::cout << sql << "success-> " << n << std::endl;
    }
    
    MYSQL_RES *res = mysql_store_result(mysql);
    if(res == nullptr) {
        std::cerr << "mysql store error" << std::endl;
        return 4;
    }

    // 获取行
    int row = mysql_num_rows(res);
    // 获取列
    int col = mysql_num_fields(res);

    // 获取列属性
    MYSQL_FIELD *head = mysql_fetch_fields(res);
    for(int i=0; i<col; i++) {
        std::cout << head[i].name << "\t";
    }
    std::cout << "\n";

    // 打印表内容
    for(int i=0; i<row; i++) {
        MYSQL_ROW one_line = mysql_fetch_row(res);
        for(int j=0; j<col; j++) {
            std::cout << one_line[j] << "\t";
        }
        std::cout << "\n";
    }


    //std::string sql;
    //while(true) {
    //    std::cout << "mysql>>> ";
    //    if(!std::getline(std::cin, sql) || sql == "quit") {
    //        std::cout << "mysql>>> bye" << std::endl;
    //        break;
    //    }
    //    int n = mysql_query(mysql, sql.c_str());
    //    if(n != 0) {
    //        std::cerr << sql << "fail-> " << n << std::endl;
    //    }else {
    //        std::cout << sql << "success-> " << n << std::endl;
    //    }
    //}

    // 释放结果集
    mysql_free_result(res);
    mysql_close(mysql);
    return 0;
}